<?php
namespace app\index\controller;
use app\common\controller\Frontend;
use app\common\library\Token;
use think\Db;
use think\Request;
class Sfpay extends Frontend
{
  //爱财支付
    protected $noNeedLogin = ['yybpay','yybback'];//需要登陆
    protected $noNeedRight = '*';//需要认证
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //$this->game=new Game($this->view->site,$this->view->user);
        $this->todaystr=strtotime(date('Ymd'));
        $this->addon=get_addon_config('Pay');

        $this->appid=$this->view->site['sfpayid'];
    	$this->appkey=$this->view->site['sfpaykey']; 
    	$this->payip=$this->view->site['sfpayip'];
    	$this->paywang=$this->view->site['sfpaywang'];
    	$this->payname='sfpay';
    	$this->baseaa=10;//最低支付金额
      //$this->paywx='';//微信通道
      $this->payWayId=8018;//wx   8003  ali  8007
    }
    public function index()
    {
      echo 'error';
       //return $this->fetch("game/pay/index.html");
    }

public function yybpay()
    {  

    $money=intval($this->request->param('aa'))>=$this->baseaa?intval($this->request->param('aa')):$this->baseaa;
if($money>200){
        $this->success('充值最大金额200','/index/biquan/index');
    }
        $uid=$this->request->param('uid');
  
  $ug = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
     if( stripos($ug,'micromessenger') !== false ){
      //微信端
      $this->assign('payurl',$this->view->site['site_url'].'/index/bypay/yybpay/aa/'.$money.'/uid/'.$uid);
      return $this->fetch("game/mapay/bypay.html"); 
     }
    
    $xmoney=$money;
    //避免生成大量废单
    $time_str=time();
    $datas['uid']=$uid;
    $datas['cash_fee']=$xmoney;
 
        //$orderid=$uid.time().$uid;
        $xoid=md5($this->todaystr.$this->auth->id.$time_str.$this->view->site['token']);
        $orderid=$xoid."_".time();
        $orderid=substr($orderid,0,20);
        $datas['out_trade_no']=$orderid;
        $datas['trade_type']=$this->payname;
        $datas['total_fee']=$xmoney;
        $datas['createtime']=time();
        $datas['status']=0;
        $idx=Db::name('history')->insert($datas);


$returnurl=$this->view->site['site_url']."/index.php/index/".$this->view->site['default_game']."/index.html";
  $price=number_format(floatval($money),2,".","");//金额(必须保留两位小数点，否则验签失败)
  $notify_url=$this->view->site['site_url']."/index.php/Index/".$this->payname."/yybback.html";//异步通知地址
 // $sign=md5('name='.$name.'&pay_type='.$pay_type.'&price='.$price.'&order_id='.$order_id.'&notify_url='.$notify_url.$key);//MD5加密串
  //--------------------------------


        $data = array(
                
                'mchId' => $this->appid,
                'productId' => $this->payWayId,
                'mchOrderNo' => $orderid,
                'amount' => $money*100,
                'returnUrl' => $returnurl,
                'notifyUrl' => $notify_url,
                'subject' => time(),
                'body' => time(),
	    
	    );

	
	

        ksort($data);
        $str1 = '';
        foreach ($data as $k => $v) {
            $str1 .=  $k . "=" . $v.'&' ;
        }
    
        $sign = strtoupper(md5($str1 .'key='. $this->appkey));
    
        $data['sign'] = $sign;
	
	
	

      $url=$this->paywang;
        //print_r($data);exit;
      //$this->formSubmit($url,$data,'支付跳转中。。。');exit;
      $return = $this->curl_file_post_contents($url,$data);
      $result = json_decode($return, true);
      //print_r($result);exit;

        if ( $result['retCode'] != 'SUCCESS') {
            print_r($result);exit;
        }else{

           $root_path = $result['payUrl'];
            header('location: '.$root_path);exit;
        }

}

private function formSubmit($url,$data,$notice=''){
  $html = '<form id="submitForm" name="submitForm" action="'.$url.'" method="post">';
  foreach($data as $pk=>$pv){
    $html.= '<input type="hidden" name="'.$pk.'" value="'.$pv.'"/>';
  }
  $html .= '</form>';

  $html .= '<script>document.forms["submitForm"].submit();</script>';
  $html.=empty($notice)?'跳转中...':$notice;

  echo $html;
  exit;
}

private function jxsave($orderid="",$free=0){
    $dat='';
    $dat=$dat==null?$this->request->param():$dat;
    $msg=''; 
    $map['out_trade_no']=$orderid;
    $map['cash_fee']=$free;
    $map['status']=0;
    $uid=Db::name('history')->where($map)->value('uid');
    $time_str=Db::name('history')->where($map)->value('createtime');
    $xmoney=intval($free);
    $str=$this->todaystr.$uid.$time_str.$this->view->site['token'];
    $orderid=md5($str);
    $odat=explode('_',$orderid);
    if($orderid==$odat[0]){
      $msg="ok";
    }else{
      $msg="fail order pass by jxsave";
    }
    return $msg;
  }

private function txt_output($i=1,$contents){
    $fp=fopen($i.".txt","w");//写文件输出用于检测先删掉4.txt
    fwrite($fp,$contents);
    fclose($fp);
    return true;
}


public function yybback(){
  $datas=array();
  $dat=$this->request->param();
  $msg='';
  $ip=$this->request->ip();  
  $link='';
  foreach ($dat as $key => $dd) {
    $link.='&'.$key.'='.$dd;
  }
  $this->txt_output($this->payname."/".$this->payname.time().'-'.$ip,$link);

   $ip=$this->request->ip();  
  if($ip!=$this->payip){
    return 'falesoop';
  } 
   
  $jxok=$this->jxsave($dat["mchOrderNo"],$dat['amount']/100);  
    if($jxok!="ok"){
      return;exit;
    }

  $datas=array();
  $dat=$this->request->param();
  $msg='';
  $map['out_trade_no']=!empty($dat['mchOrderNo'])?$dat['mchOrderNo']:'empty';
  $map['cash_fee']=$dat['amount']/100;
  $map['trade_type']=$this->payname;
  $map['status']=0;
  $idx=Db::name('history')->where($map)->count();//查询订单是否存在
  
  //echo $idx;exit;
  if ($idx>0) {
  		
           
            ksort($dat);
            $str1 = '';
            foreach ($dat as $k => $v) {
                if($k=='sign' || $v==''){ continue;}
                $str1 .=  $k . "=" . $v.'&';
            }
            $sign=strtoupper(md5($str1 .'key='. $this->appkey));
    // if($dat['returncode']!='00'){
    //     print_r($dat['returncode']);exit;
    // }

      if (!isset($dat['sign'])) {
         print_r($dat);
         echo "error";exit;
      }
        if($sign != $dat['sign']){
           $msg= 'fail error key';
        }else{
            //更新订单
              $hmap['transaction_id']=$dat['mchOrderNo'];
              $hmap['note']=$dat['mchOrderNo'];
              $hmap['attach']=$dat['sign'];
              Db::name('history')->where($map)->update($hmap);  
              $uid=Db::name('history')->where($map)->value('uid');
              // $this->txt_output('del/yybback'.time().$uid,json_encode($this->request->param()));
              if ($uid>0) {
                 db::name('user')->where('id='.$uid)->setInc('point',$dat['amount']/100);//上分
                 Db::name('history')->where($map)->setfield('status',1);
                 //记录收入
                 $tomap['createtime']=$this->todaystr;
                 db::name('run_count')->where($tomap)->setInc('srpay',intval($dat['amount']));
                 $tomap['uid']=$uid;
                 db::name('user_count')->where($tomap)->setInc('srpay',intval($dat['amount']));
              }  
              $msg='success';
        }
  }else{
      $msg='faill';
  }
 
  echo $msg;
  exit;
}

public function is_sign($row,$signKey){ #效验服务器返回数据
    $r_sign = $row['sign']; #保留签名数据
    $arr = array();
    foreach ($row as $key=>$v){
      if ($key !== 'sign'){ #删除签名
        $arr[$key] = $v;
      }
    }
    ksort($arr);
    $sign = strtouPPer(md5(json_encode($arr) . $signKey)); #生成签名
    if ($sign == $r_sign){
      return true;
    }else{
      return false;
    }

  }

private function curl_file_post_contents($durl, $post_data){
    // header传送格式
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $durl);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, false);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, true);
    // 设置post请求参数
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    // CURLINFO_HEADER_OUT选项可以拿到请求头信息
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);
    // 不验证SSL
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    //执行命令
    $data = curl_exec($curl);
    // 打印请求头信息
    //        echo curl_getinfo($curl, CURLINFO_HEADER_OUT);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    return $data;
} 
private function getHttpContent($url, $method = 'GET', $postData = []) {
        $data       = '';
        // $user_agent = $_SERVER ['HTTP_USER_AGENT'];
        // $header     = [
        //     "User-Agent:".$user_agent
        // ];
        if (!empty($url)) {
            try {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 30); //30秒超时
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                //curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
                if (strstr($url, 'https://')) {
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                }
    
                if (strtoupper($method) == 'POST') {
                    $curlPost = is_array($postData) ? http_build_query($postData) : $postData;
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
                }
                $data = curl_exec($ch);
                curl_close($ch);
            } catch (Exception $e) {
                $data = '';
            }
        }
        return $data;
    }

}
